// yyyy-MM-dd hh:mm:ss.SSS 所有支持的类型
function pad(str, length = 2) {
	str = String(str)
	while (str.length < length) {
		str = `0${str}`
	}
	return str.slice(-length)
}

const parser = {
	yyyy: (dateObj) => pad(dateObj.year, 4),
	yy: (dateObj) => pad(dateObj.year),
	MM: (dateObj) => pad(dateObj.month),
	M: (dateObj) => dateObj.month,
	dd: (dateObj) => pad(dateObj.day),
	d: (dateObj) => dateObj.day,
	hh: (dateObj) => pad(dateObj.hour),
	h: (dateObj) => dateObj.hour,
	mm: (dateObj) => pad(dateObj.minute),
	m: (dateObj) => dateObj.minute,
	ss: (dateObj) => pad(dateObj.second),
	s: (dateObj) => dateObj.second,
	SSS: (dateObj) => pad(dateObj.millisecond, 3),
	S: (dateObj) => dateObj.millisecond,
}

// 这都n年了iOS依然不认识2020-12-12，需要转换为2020/12/12
function getDate(time) {
	if (time instanceof Date) {
		return time
	}
	switch (typeof time) {
		case 'string': {
			// 2020-12-12T12:12:12.000Z、2020-12-12T12:12:12.000
			if (time.indexOf('T') > -1) {
				return new Date(time)
			}
			return new Date(time.replace(/-/g, '/'))
		}
		default:
			return new Date(time)
	}
}


export function formatDate(date, format = 'yyyy-MM-dd') {
	if (!date && date !== 0) {
		return ''
	}
	date = getDate(date)
	const dateObj = {
		year: date.getFullYear(),
		month: date.getMonth() + 1,
		day: date.getDate(),
		hour: date.getHours(),
		minute: date.getMinutes(),
		second: date.getSeconds(),
		millisecond: date.getMilliseconds(),
	}
	const tokenRegExp = /yyyy|yy|MM|M|dd|d|hh|h|mm|m|ss|s|SSS|SS|S/
	let flag = true
	let result = format
	while (flag) {
		flag = false
		result = result.replace(tokenRegExp, function(matched) {
			flag = true
			return parser[matched](dateObj)
		})
	}
	return result
}

/**
 * 倒计时提示
 * @param workingDateStart {Date | String | Number} 时间
 * @param workingDateEnd {Date | String | Number} 时间
 * @returns {String}
 */
export const countDown = function(workingDateStart, workingDateEnd, title = '') {
	const begDate = new Date(workingDateStart)
	const endDate = new Date(workingDateEnd)

	const end = endDate.getTime() // 结束秒数
	const beg = begDate.getTime() // 开始秒数
	// 获取当前时间
	const date = new Date()
	const now = date.getTime()
	// 时间差
	const leftTime = end - now // 结束秒数 - 现在秒数
	const begTime = beg - now // 开始秒数 - 现在秒数
	// 定义变量 d,h,m,s保存倒计时的时间
	let d, h, m, s
	let timeTit = ''
	const calc = (time) => {
		d = Math.floor(time / 1000 / 60 / 60 / 24)
		h = Math.floor(time / 1000 / 60 / 60 % 24)
		m = Math.floor(time / 1000 / 60 % 60)
		s = Math.floor(time / 1000 % 60)
		if (d > 0) timeTit += `${d}天`
		if (h > 0) timeTit += `${h < 10 ? `0${h}` : h}:`
		timeTit += `${m < 10 ? `0${m}` : m}:${s < 10 ? `0${s}` : s}`
	}
	if (begTime >= 0) {
		timeTit = `距离${title}开始还有`
		calc(begTime)
	} else if (leftTime >= 0) {
		timeTit = `距离${title}结束还有`
		calc(leftTime)
	} else {
		timeTit = `${title}已结束`
	}
	return timeTit
}


export function friendlyDate(time, {
	locale = 'zh',
	threshold = [60000, 3600000],
	format = 'yyyy/MM/dd hh:mm:ss',
}) {
	if (time === '-') {
		return time
	}
	if (!time && time !== 0) {
		return ''
	}
	const localeText = {
		zh: {
			year: '年',
			month: '月',
			day: '天',
			hour: '小时',
			minute: '分钟',
			second: '秒',
			ago: '前',
			later: '后',
			justNow: '刚刚',
			soon: '马上',
			template: '{num}{unit}{suffix}',
		},
		en: {
			year: 'year',
			month: 'month',
			day: 'day',
			hour: 'hour',
			minute: 'minute',
			second: 'second',
			ago: 'ago',
			later: 'later',
			justNow: 'just now',
			soon: 'soon',
			template: '{num} {unit} {suffix}',
		},
	}
	const text = localeText[locale] || localeText.zh
	const date = getDate(time)
	let ms = date.getTime() - Date.now()
	const absMs = Math.abs(ms)
	if (absMs < threshold[0]) {
		return ms < 0 ? text.justNow : text.soon
	}
	if (absMs >= threshold[1]) {
		return formatDate(date, format)
	}
	let num
	let unit
	let suffix = text.later
	if (ms < 0) {
		suffix = text.ago
		ms = -ms
	}
	const seconds = Math.floor(ms / 1000)
	const minutes = Math.floor(seconds / 60)
	const hours = Math.floor(minutes / 60)
	const days = Math.floor(hours / 24)
	const months = Math.floor(days / 30)
	const years = Math.floor(months / 12)
	switch (true) {
		case years > 0:
			num = years
			unit = text.year
			break
		case months > 0:
			num = months
			unit = text.month
			break
		case days > 0:
			num = days
			unit = text.day
			break
		case hours > 0:
			num = hours
			unit = text.hour
			break
		case minutes > 0:
			num = minutes
			unit = text.minute
			break
		default:
			num = seconds
			unit = text.second
			break
	}

	if (locale === 'en') {
		if (num === 1) {
			num = 'a'
		} else {
			unit += 's'
		}
	}

	return text.template.replace(/{\s*num\s*}/g, `${num}`).replace(/{\s*unit\s*}/g, unit).replace(/{\s*suffix\s*}/g,
		suffix)
}



export const formatSeconds = (value) => {
	//  秒
	let second = parseInt(value)
	//  分
	let minute = 0
	//  小时
	let hour = 0
	//  天
	//  let day = 0
	//  如果秒数大于60，将秒数转换成整数
	if (second > 60) {
		//  获取分钟，除以60取整数，得到整数分钟
		minute = parseInt(second / 60)
		//  获取秒数，秒数取佘，得到整数秒数
		second = parseInt(second % 60)
		//  如果分钟大于60，将分钟转换成小时
		if (minute > 60) {
			//  获取小时，获取分钟除以60，得到整数小时
			hour = parseInt(minute / 60)
			//  获取小时后取佘的分，获取分钟除以60取佘的分
			minute = parseInt(minute % 60)
			//  如果小时大于24，将小时转换成天
			//  if (hour > 23) {
			//    //  获取天数，获取小时除以24，得到整天数
			//    day = parseInt(hour / 24)
			//    //  获取天数后取余的小时，获取小时除以24取余的小时
			//    hour = parseInt(hour % 24)
			//  }
		}
	}

	let result = '' + parseInt(second) + '秒'
	if (minute > 0) {
		result = '' + parseInt(minute) + '分' + result
	}
	if (hour > 0) {
		result = '' + parseInt(hour) + '小时' + result
	}
	//  if (day > 0) {
	//    result = '' + parseInt(day) + '天' + result
	//  }
	console.log('result：', result)
	return result
}
